<?php

namespace app\common\controller;

use app\admin\model\money\Change;
use app\admin\model\product\Order;
use app\admin\model\User;
use app\admin\model\user\Finance;
use app\admin\model\user\Statics;
use app\common\model\Config;
use think\Console;

final class Payment
{
    private static $appId = '';
    private static $cusId = '';
    private static $apiUrl = "";
    private static $apiVersion = '11';
    private static $notifyUrl = '';

    public function __construct()
    {
        self::$appId = "00317165";
        self::$cusId = "https://vsp.allinpay.com/apiweb/unitorder";
        self::$apiUrl = "https://vsp.allinpay.com/apiweb/unitorder";//生产环境
        self::$notifyUrl = "https://vsp.allinpay.com/apiweb/unitorder";//生产环境
    }

    function pay($data)
    {
        $params = array();
        $params["cusid"] = self::$cusId;
        $params["appid"] = self::$appId;
        $params["version"] = self::$apiVersion;
        $params["orgid"] = '';
        $params["trxamt"] = 1;
        $params["reqsn"] = 123;
        $params["paytype"] = 'W06';
        $params["body"] = $data['body'];
        $params["remark"] = $data['remark'];
        $params["validtime"] = 12;
        $params["acct"] = 'oM4tN4x6Cdp51AYTZCYzPN2E8gLU';
        $params["notify_url"] = self::$notifyUrl;
        $params["limit_pay"] = '';
        $params["sub_appid"] = 'wx58959207ed2673ca';
        $params["subbranch"] = '';
        $params["cusip"] = '';
        $params["idno"] = '';
        $params["truename"] = '';
        $params["fqnum"] = '';
        $params["randomstr"] = 12;
        $params["signtype"] = 'RSA';
        $params["front_url"] = 'https://suppliershop.liancaiwang.cn/api/public/index.php/h5/pay/payApply';
        $params["sign"] = urlencode(self::makeSign($params));//签名
        $paramsStr = self::ToUrlParams($params);
        $url = self::$apiUrl . "/pay";
        $rsp = $this->request($url, $paramsStr);
        echo "请求返回:" . $rsp;
        echo "<br/>";
        $rspArray = json_decode($rsp, true);
        if (self::validSign($rspArray)) {
            echo "验签正确,进行业务处理";
        }

    }


//统一被扫接口
    function scanqrpay()
    {
        $params = array();
        $params["cusid"] = AppConfig::CUSID;
        $params["appid"] = AppConfig::APPID;
        $params["version"] = AppConfig::APIVERSION;
        $params["orgid"] = $orgid;
        $params["version"] = $version;
        $params["trxamt"] = $trxamt;
        $params["reqsn"] = $reqsn;
        $params["body"] = $body;
        $params["remark"] = $remark;
        $params["authcode"] = $authcode;
        $params["limit_pay"] = $limit_pay;
        $params["subbranch"] = $subbranch;
        $params["asinfo"] = $asinfo;
        $params["idno"] = $idno;
        $params["truename"] = $truename;
        $params["randomstr"] = $randomstr;
        $params["fqnum"] = $fqnum;
        $params["signtype"] = 'RSA';
        $params["sign"] = urlencode(AppUtil::Sign($params));//签名
        $paramsStr = AppUtil::ToUrlParams($params);
        $url = AppConfig::APIURL . "/pay";
        $rsp = request($url, $paramsStr);
        echo "请求返回:" . $rsp;
        echo "<br/>";
        $rspArray = json_decode($rsp, true);
        if (AppUtil::validSign($rspArray)) {
            echo "验签正确,进行业务处理";
            echo "验签正确,进行业务处理";
        }

    }


//当天交易用撤销
    function cancel()
    {
        $params = array();
        $params["cusid"] = AppConfig::CUSID;
        $params["appid"] = AppConfig::APPID;
        $params["version"] = AppConfig::APIVERSION;
        $params["trxamt"] = "1";
        $params["reqsn"] = "123456788";
        $params["signtype"] = 'RSA';
        $params["oldreqsn"] = "123456";//原来订单号
        $params["randomstr"] = "1450432107647";//
        $params["sign"] = urlencode(AppUtil::Sign($params));//签名
        $paramsStr = AppUtil::ToUrlParams($params);
        $url = AppConfig::APIURL . "/cancel";
        $rsp = request($url, $paramsStr);
        echo "请求返回:" . $rsp;
        echo "<br/>";
        $rspArray = json_decode($rsp, true);
        if (AppUtil::validSign($rspArray)) {
            echo "验签正确,进行业务处理";
        }
    }

//当天交易请用撤销,非当天交易才用此退货接口
    function refund()
    {
        $params = array();
        $params["cusid"] = AppConfig::CUSID;
        $params["appid"] = AppConfig::APPID;
        $params["version"] = AppConfig::APIVERSION;
        $params["trxamt"] = "1";
        $params["reqsn"] = "1234567889";
        $params["oldreqsn"] = "123456";//原来订单号
        $params["randomstr"] = "1450432107647";//
        $params["signtype"] = 'RSA';
        $params["sign"] = urlencode(AppUtil::Sign($params));//签名
        $paramsStr = AppUtil::ToUrlParams($params);
        $url = AppConfig::APIURL . "/refund";
        $rsp = request($url, $paramsStr);
        echo "请求返回:" . $rsp;
        echo "<br/>";
        $rspArray = json_decode($rsp, true);
        if (AppUtil::validSign($rspArray)) {
            echo "验签正确,进行业务处理";
        }
    }

    function query()
    {
        $params = array();
        $params["cusid"] = AppConfig::CUSID;
        $params["appid"] = AppConfig::APPID;
        $params["version"] = AppConfig::APIVERSION;
        $params["reqsn"] = "123456";
        $params["randomstr"] = "1450432107647";//
        $params["signtype"] = 'RSA';
        $params["sign"] = urlencode(AppUtil::Sign($params));//签名
        $paramsStr = AppUtil::ToUrlParams($params);
        $url = AppConfig::APIURL . "/query";
        $rsp = request($url, $paramsStr);
        echo "请求返回:" . $rsp;
        echo "<br/>";
        $rspArray = json_decode($rsp, true);
        if (AppUtil::validSign($rspArray)) {
            echo "验签正确,进行业务处理";
        }
    }

//发送请求操作仅供参考,不为最佳实践
    function request($url, $params)
    {
        $ch = curl_init();
        $this_header = array("content-type: application/x-www-form-urlencoded;charset=UTF-8");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//如果不加验证,就设false,商户自行处理
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    //验签
    static function validSign($array)
    {
        if ("SUCCESS" == $array["retcode"]) {
            $signRsp = strtolower($array["sign"]);
            $array["sign"] = "";
            $sign = strtolower(self::makeSign($array));
            if ($sign == $signRsp) {
                return TRUE;
            } else {
                echo "验签失败:" . $signRsp . "--" . $sign;
            }
        } else {
            echo $array["retmsg"];
        }

        return FALSE;
    }

    /**
     * 将参数数组签名
     */
    private static function makeSign(array $array)
    {
        ksort($array);
        $bufSignSrc = self::ToUrlParams($array);
        $private_key = 'MIIEowIBAAKCAQEAnlGKzchX0aOn9xRVuRgQRp7Oc0a5ArogQA1tOcf7sSq+M2+2bTmCxQChBrwJAo7d68jiZKRzYLTfy40gEXwc+wLDPubnyPrLnoVDubVxNXOLdF6lpm28wOO5xn1Daqd+E9l+wjhcbcUvVOSU12SXcfmwCh4lsdbTyeOFB8qlqzPvT4lGSjD+nZyiAwBgoYD13Pb2ipdAhOLfwyicv5+iWTnjNY3ZQ+5C5iajXyqXheE8/u5Gc0f+xUJx4ibYtEGx3DY/Ix7+9U2p/a9DV0KMP2xb+WPdYctqtQzX1Su3VrCGGfVCHnZGwDEvQ5eBM66/2UljDCB08TO1snu16TULPQIDAQABAoIBADzVuo+Of2hYCa/gyXvhakeouE4FjAwnN0NFpYYBeY6/jOy47ZGU+tH2hunOkWvBODdlLtFbe9ZaSnCuHvd5CK3PhvUBx2ksLdgQ/1A6D3Fpn9mskNyd6Fz6ZKWH9sLh74lzFslM3P91ONXXK/aEeclbF7EbmoJ2uVUnrzOqQ/S/2lhkgycoaCj1OC8fID5dQzmZcBVx+d++B2N96as2vqCuOW2pBTAciDIVTJNomzcahvu3fiVSswJ5j08LX8ZxT5v3soET3eo40pZMzC8H03y6LDEKsig1588YcEnGizgH8622lLnrOW3IAedSCr1bwOMQ98hWvc5r2vrZ4xoPBkUCgYEAz3nJyjUhq3KgCeDNnuhTdqZ+fL1ZrOk9T7+OM3mW/WHThQXQ4ayFwOU9F30CZLImphskUk+ebZnIl8M+/8+klzhjRgty5lfzTjbZCREKoegcqczeKLLzpAzi9K8FHlpJYHkT9+E5QsLc1BFpJwAUbwjx6Hwqxz9BUcSCovDVyTMCgYEAw1iPao9loz0RQmyOb7ufWw4gdyEdvrFPgnAOh/ZSOXs382NS7nOEMh26CTKV1pZkb2d4FNgIL1rSThVnb/c3QSeOjcbSUZ9T58FvW20Pn7hTMZuIGlRjit+AqCfr2cklcyJgd5poDZstI/5Y56bTIO+NMfyyFgXbZuFuEgFJOc8CgYALWW0pa4ig+U852xtEYw8VwXvP1QfPxp58+0yLEk6pI63PbAcGIUrbx251F3iHC5vDoF53RjWzZyMq8hpDIhet0f7UORIa+Zqsn6F1toHvY2QWAcfxUAC166KKofxUsbmr1lO6To60UTaFP0KSSJXVkRaykgBBD/vBvk8rHKOFMwKBgQCxSfPHW2N8FlVOuqU/BMIo6pZOaDDNu7CUiky12rlfT9REwXUn0pE8xrvr0wwoWA/JB9f02uf6ymup0EUzWeO870Cyrap9x6Nn56fACygt5iUjFawdcU9yX0wt0SV9X8/sQVvZ0Ln090utqg5YF5DwCFlV76hU0nYAVkIGd0JVAwKBgCOkJvO1jlE3e2f3KqdtiL9rl2JoUohdSPXrDONn6NwyBOS57bSj0U/4wu1x1zZnKcJZzol+5prnSg/ijfGlvJ3sTw1XGI9m3pYlh/5/Jk/cVox5MjQZwLt0UDoUob8Ft0LtWTNn36UsvwVeDaU3HF+y5zitBYdzbgZ53XFXTREt';
        $private_key = chunk_split($private_key, 64, "\n");
        $key = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($private_key) . "-----END RSA PRIVATE KEY-----";
        //   echo $key;
        if (openssl_sign($bufSignSrc, $signature, $key)) {
            //		echo 'sign success';
        } else {
            echo 'sign fail';
        }
        $sign = base64_encode($signature);//加密后的内容通常含有特殊字符，需要编码转换下，在网络间通过url传输时要注意base64编码是否是url安全的

        return $sign;

    }

    private static function ToUrlParams(array $array)
    {
        $buff = "";
        foreach ($array as $k => $v) {
            if ($v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     * 校验签名
     * @param array 参数
     * @param unknown_type appkey
     */


    public function notify()
    {
        $params = array();
        foreach ($_POST as $key => $val) {//动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
            $params[$key] = $val;
        }
        if (count($params) < 1) {//如果参数为空,则不进行处理
            echo "error";
            exit();
        }
        if (AppUtil::ValidSign($params)) {//验签成功
            //此处进行业务逻辑处理
            echo "success";
        } else {
            echo "erro";
        }
    }

}